<template>
  <!-- 线边库（新增表）表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1200px"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="100"
    >
      <el-form-item label="生产日期">
        <el-date-picker
          v-model="formData.planActualDateSearch"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="getplanActualDate"
          :disabled-date="(e) => disabledPastDate(e)"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTimeList"
          ><i-ep-search />搜索</el-button
        >
        <el-button @click="restartTimeSearch"><i-ep-refresh />重置</el-button>
      </el-form-item>

      <div style="font-size: 14px; font-weight: 700">外部</div>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="formData.tableData1"
        highlight-current-row
        border
        max-height="200px"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
          label="产品名称"
          prop="materialName"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="生产批次号"
          prop="plannedBatch"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="生产日期"
          prop="planActualDate"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />

        <el-table-column
          label="计划数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="返修类型"
          prop="processesClassification"
          min-width="130"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.processesClassification === 18"
              >内部返修</span
            >
            <span v-if="scope.row.processesClassification === 19"
              >外部返修</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="上工序完成时间"
          prop="lastProcessFinshTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="理论时长(分)"
          prop="theoreticalTime"
          min-width="120"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="计划开始时间"
          prop="planBeginTime"
          min-width="200"
          align="center"
        >
          <template #default="{ $index, row }">
            <el-form-item
              :prop="'tableData1.' + $index + '.planBeginTime'"
              :rules="rules.planBeginTime"
              class="right-input"
              style="width: 100%"
            >
              <el-date-picker
                style="width: 100%"
                v-model="row.planBeginTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划开始时间"
                :disabled-date="(e) => disabledBeginTime(e, row, $index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="计划结束时间"
          prop="planEndTime"
          min-width="200"
          align="center"
        >
          <template #default="{ $index, row }">
            <el-form-item
              :prop="'tableData1.' + $index + '.planEndTime'"
              :rules="rules.planEndTime"
              class="right-input"
              style="width: 100%"
            >
              <el-date-picker
                v-model="row.planEndTime"
                style="width: 100%"
                :disabled="!row.planBeginTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划结束时间"
                :disabled-date="(e) => disabledBeginTime3(e, row, $index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      <div style="font-size: 14px; font-weight: 700; margin-top: 10px">
        内部
      </div>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="formData.tableData2"
        highlight-current-row
        border
        max-height="200px"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
          label="产品名称"
          prop="materialName"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="生产批次号"
          prop="plannedBatch"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="生产日期"
          prop="planActualDate"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />

        <el-table-column
          label="计划数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="返修类型"
          prop="processesClassification"
          min-width="130"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.processesClassification === 18"
              >内部返修</span
            >
            <span v-if="scope.row.processesClassification === 19"
              >外部返修</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="上工序完成时间"
          prop="lastProcessFinshTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="理论时长(分)"
          prop="theoreticalTime"
          min-width="120"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="计划开始时间"
          prop="planBeginTime"
          min-width="200"
          align="center"
        >
          <template #default="{ $index, row }">
            <el-form-item
              :prop="'tableData2.' + $index + '.planBeginTime'"
              :rules="rules.planBeginTime"
              class="right-input"
              style="width: 100%"
            >
              <el-date-picker
                v-model="row.planBeginTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划开始时间"
                :disabled-date="
                  (e) =>
                    disabledBeginTime2(e, row, $index) ||
                    (row.lastProcessFinshTime &&
                      new Date(e) < new Date(row.lastProcessFinshTime))
                "
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="计划结束时间"
          prop="planEndTime"
          min-width="200"
          align="center"
        >
          <template #default="{ $index, row }">
            <el-form-item
              :prop="'tableData2.' + $index + '.planEndTime'"
              :rules="rules.planEndTime"
              class="right-input"
              style="width: 100%"
            >
              <el-date-picker
                style="width: 100%"
                v-model="row.planEndTime"
                type="datetime"
                :disabled="!row.planBeginTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划结束时间"
                :disabled-date="(e) => disabledBeginTime4(e, row, $index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";
import { rest } from "lodash";

defineOptions({
  name: "REPAIRTIMESETTINGEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    // 默认选中当前日期范围

    formData.planActualDateStart = dayjs(new Date()).format("YYYY-MM-DD");
    formData.planActualDateEnd = dayjs(new Date()).format("YYYY-MM-DD");

    formData.planActualDateSearch = [
      dayjs(new Date()).format("YYYY-MM-DD"),
      dayjs(new Date()).format("YYYY-MM-DD"),
    ];
    getTimeList();
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  planBeginTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        const rowIndex = rule.field.split(".")[1];
        const tableName = rule.field.split(".")[0];
        const row = formData[tableName][rowIndex];
        if (
          row.lastProcessFinshTime &&
          new Date(value) < new Date(row.lastProcessFinshTime)
        ) {
          callback(new Error("不能小于上工序完成时间"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  planEndTime: [
    { required: true, message: "请选择计划结束时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        console.log(11);

        const rowIndex = rule.field.split(".")[1];
        const tableName = rule.field.split(".")[0];
        const row = formData[tableName][rowIndex];
        console.log(new Date(value), new Date(row.planBeginTime));

        if (
          row.planBeginTime &&
          new Date(value) < new Date(row.planBeginTime)
        ) {
          callback(new Error("结束时间不能小于开始时间"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});
// 禁用当前日期之前日期(不包含当天日期)
const disabledPastDate = (date: Date) => {
  return date < new Date(new Date().setHours(0, 0, 0, 0));
};
const formRef = ref(ElForm);

let formData = reactive({
  planActualDateEnd: "",
  planActualDateStart: "",
  planActualDateSearch: [],

  tableData1: [],

  tableData2: [],
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.planActualDateEnd = "";
  formData.planActualDateStart = "";
  formData.planActualDateSearch = [];

  formData.tableData1 = [];

  formData.tableData2 = [];
}

const loading = ref(false);

/** 线边库（新增表）保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;

      await request({
        url: "/mes/mesplanworkingform/adjustTimeFixSave",
        method: "post",
        data: [...formData.tableData1, ...formData.tableData2],
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`提交成功！`);
      closeDialog();
      emit("reset-table");
    }
  });
}

function getplanActualDate(data: any) {
  if (data) {
    formData.planActualDateStart = data[0];
    formData.planActualDateEnd = data[1];
  } else {
    formData.planActualDateStart = "";
    formData.planActualDateEnd = "";
  }
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

// 禁用当前日期之前日期(不包含当天日期)
const disabledBeginTime = (time: Date, row, index) => {
  if (
    time.getTime() <
    dayjs(formData.tableData1[index]?.lastProcessFinshTime).valueOf()
  ) {
    return true;
  }

  return false;
};
const disabledBeginTime2 = (time: Date, row, index) => {
  if (
    time.getTime() <
    dayjs(formData.tableData2[index]?.lastProcessFinshTime).valueOf()
  ) {
    return true;
  }

  return false;
};
const disabledBeginTime3 = (time: Date, row, index) => {
  if (
    time.getTime() < dayjs(formData.tableData1[index]?.planBeginTime).valueOf()
  ) {
    return true;
  }

  return false;
};
const disabledBeginTime4 = (time: Date, row, index) => {
  if (
    time.getTime() < dayjs(formData.tableData2[index]?.planBeginTime).valueOf()
  ) {
    return true;
  }

  return false;
};
const getTimeList = async () => {
  await request({
    url: "/mes/mesplanworkingform/queryByList",
    method: "post",
    data: {
      planActualDateSearch: formData.planActualDateSearch || [],
      planActualDateStart: formData.planActualDateStart || "",
      planActualDateEnd: formData.planActualDateEnd || "",
      processesClassifications: [18, 19],
    },
  })
    .then((res) => {
      console.log(res.data);
      formData.tableData1 = [] as any;
      formData.tableData2 = [] as any;
      formData.tableData1 =
        res.data.filter((item: any) => item.processesClassification == "19") ||
        [];
      formData.tableData2 =
        res.data.filter((item: any) => item.processesClassification == "18") ||
        [];
    })
    .finally(() => {
      // loading.value = false;
    });
};

// 重置表单
const restartTimeSearch = () => {
  formData.planActualDateSearch = [];
  formData.planActualDateStart = "";
  formData.planActualDateEnd = "";
  // 默认选中当前日期范围
  formData.planActualDateStart = dayjs(new Date()).format("YYYY-MM-DD");
  formData.planActualDateEnd = dayjs(new Date()).format("YYYY-MM-DD");

  formData.planActualDateSearch = [
    dayjs(new Date()).format("YYYY-MM-DD"),
    dayjs(new Date()).format("YYYY-MM-DD"),
  ];
  getTimeList();
};
</script>
